
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logging HOWTO &#8212; Python 3.6.3 documentation</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.6.3',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true,
        SOURCELINK_SUFFIX: '.txt'
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.6.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Logging Cookbook" href="logging-cookbook.html" />
    <link rel="prev" title="Functional Programming HOWTO" href="functional.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/howto/logging.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/switchers.js"></script>
    
    
 

  </head>
  <body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="functional.html" title="Functional Programming HOWTO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">en</span>
          <span class="version_switcher_placeholder">3.6.3</span>
          <a href="../index.html">Documentation </a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="logging-howto">
<h1>Logging HOWTO<a class="headerlink" href="#logging-howto" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Vinay Sajip &lt;vinay_sajip at red-dove dot com&gt;</td>
</tr>
</tbody>
</table>
<div class="section" id="basic-logging-tutorial">
<span id="logging-basic-tutorial"></span><h2>Basic Logging Tutorial<a class="headerlink" href="#basic-logging-tutorial" title="Permalink to this headline">¶</a></h2>
<p>Logging is a means of tracking events that happen when some software runs. The
software’s developer adds logging calls to their code to indicate that certain
events have occurred. An event is described by a descriptive message which can
optionally contain variable data (i.e. data that is potentially different for
each occurrence of the event). Events also have an importance which the
developer ascribes to the event; the importance can also be called the <em>level</em>
or <em>severity</em>.</p>
<div class="section" id="when-to-use-logging">
<h3>When to use logging<a class="headerlink" href="#when-to-use-logging" title="Permalink to this headline">¶</a></h3>
<p>Logging provides a set of convenience functions for simple logging usage. These
are <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">error()</span></code></a> and
<a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">critical()</span></code></a>. To determine when to use logging, see the table below, which
states, for each of a set of common tasks, the best tool to use for it.</p>
<table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="51%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Task you want to perform</th>
<th class="head">The best tool for the task</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Display console output for ordinary
usage of a command line script or
program</td>
<td><a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal"><span class="pre">print()</span></code></a></td>
</tr>
<tr class="row-odd"><td>Report events that occur during
normal operation of a program (e.g.
for status monitoring or fault
investigation)</td>
<td><a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">logging.info()</span></code></a> (or
<a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">logging.debug()</span></code></a> for very
detailed output for diagnostic
purposes)</td>
</tr>
<tr class="row-even"><td>Issue a warning regarding a
particular runtime event</td>
<td><p class="first"><a class="reference internal" href="../library/warnings.html#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal"><span class="pre">warnings.warn()</span></code></a> in library
code if the issue is avoidable and
the client application should be
modified to eliminate the warning</p>
<p class="last"><a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">logging.warning()</span></code></a> if there is
nothing the client application can do
about the situation, but the event
should still be noted</p>
</td>
</tr>
<tr class="row-odd"><td>Report an error regarding a
particular runtime event</td>
<td>Raise an exception</td>
</tr>
<tr class="row-even"><td>Report suppression of an error
without raising an exception (e.g.
error handler in a long-running
server process)</td>
<td><a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">logging.error()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><code class="xref py py-func docutils literal"><span class="pre">logging.exception()</span></code></a> or
<a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">logging.critical()</span></code></a> as
appropriate for the specific error
and application domain</td>
</tr>
</tbody>
</table>
<p>The logging functions are named after the level or severity of the events
they are used to track. The standard levels and their applicability are
described below (in increasing order of severity):</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">When it’s used</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal"><span class="pre">DEBUG</span></code></td>
<td>Detailed information, typically of interest
only when diagnosing problems.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">INFO</span></code></td>
<td>Confirmation that things are working as
expected.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal"><span class="pre">WARNING</span></code></td>
<td>An indication that something unexpected
happened, or indicative of some problem in
the near future (e.g. ‘disk space low’).
The software is still working as expected.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">ERROR</span></code></td>
<td>Due to a more serious problem, the software
has not been able to perform some function.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal"><span class="pre">CRITICAL</span></code></td>
<td>A serious error, indicating that the program
itself may be unable to continue running.</td>
</tr>
</tbody>
</table>
<p>The default level is <code class="docutils literal"><span class="pre">WARNING</span></code>, which means that only events of this level
and above will be tracked, unless the logging package is configured to do
otherwise.</p>
<p>Events that are tracked can be handled in different ways. The simplest way of
handling tracked events is to print them to the console. Another common way
is to write them to a disk file.</p>
</div>
<div class="section" id="a-simple-example">
<span id="howto-minimal-example"></span><h3>A simple example<a class="headerlink" href="#a-simple-example" title="Permalink to this headline">¶</a></h3>
<p>A very simple example is:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Watch out!&#39;</span><span class="p">)</span>  <span class="c1"># will print a message to the console</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;I told you so&#39;</span><span class="p">)</span>  <span class="c1"># will not print anything</span>
</pre></div>
</div>
<p>If you type these lines into a script and run it, you’ll see:</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>WARNING:root:Watch out!
</pre></div>
</div>
<p>printed out on the console. The <code class="docutils literal"><span class="pre">INFO</span></code> message doesn’t appear because the
default level is <code class="docutils literal"><span class="pre">WARNING</span></code>. The printed message includes the indication of
the level and the description of the event provided in the logging call, i.e.
‘Watch out!’. Don’t worry about the ‘root’ part for now: it will be explained
later. The actual output can be formatted quite flexibly if you need that;
formatting options will also be explained later.</p>
</div>
<div class="section" id="logging-to-a-file">
<h3>Logging to a file<a class="headerlink" href="#logging-to-a-file" title="Permalink to this headline">¶</a></h3>
<p>A very common situation is that of recording logging events in a file, so let’s
look at that next. Be sure to try the following in a newly-started Python
interpreter, and don’t just continue from the session described above:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;example.log&#39;</span><span class="p">,</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;This message should go to the log file&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;So should this&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;And this, too&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>And now if we open the file and look at what we have, we should find the log
messages:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">DEBUG</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">This</span> <span class="n">message</span> <span class="n">should</span> <span class="n">go</span> <span class="n">to</span> <span class="n">the</span> <span class="n">log</span> <span class="n">file</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">So</span> <span class="n">should</span> <span class="n">this</span>
<span class="n">WARNING</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">And</span> <span class="n">this</span><span class="p">,</span> <span class="n">too</span>
</pre></div>
</div>
<p>This example also shows how you can set the logging level which acts as the
threshold for tracking. In this case, because we set the threshold to
<code class="docutils literal"><span class="pre">DEBUG</span></code>, all of the messages were printed.</p>
<p>If you want to set the logging level from a command-line option such as:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="o">--</span><span class="n">log</span><span class="o">=</span><span class="n">INFO</span>
</pre></div>
</div>
<p>and you have the value of the parameter passed for <code class="docutils literal"><span class="pre">--log</span></code> in some variable
<em>loglevel</em>, you can use:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="nb">getattr</span><span class="p">(</span><span class="n">logging</span><span class="p">,</span> <span class="n">loglevel</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>
</pre></div>
</div>
<p>to get the value which you’ll pass to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> via the <em>level</em>
argument. You may want to error check any user input value, perhaps as in the
following example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="c1"># assuming loglevel is bound to the string value obtained from the</span>
<span class="c1"># command line argument. Convert to upper case to allow the user to</span>
<span class="c1"># specify --log=DEBUG or --log=debug</span>
<span class="n">numeric_level</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">logging</span><span class="p">,</span> <span class="n">loglevel</span><span class="o">.</span><span class="n">upper</span><span class="p">(),</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">numeric_level</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
    <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;Invalid log level: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">loglevel</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">numeric_level</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>The call to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> should come <em>before</em> any calls to <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a> etc. As it’s intended as a one-off simple configuration facility,
only the first call will actually do anything: subsequent calls are effectively
no-ops.</p>
<p>If you run the above script several times, the messages from successive runs
are appended to the file <em>example.log</em>. If you want each run to start afresh,
not remembering the messages from earlier runs, you can specify the <em>filemode</em>
argument, by changing the call in the above example to:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;example.log&#39;</span><span class="p">,</span> <span class="n">filemode</span><span class="o">=</span><span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
</pre></div>
</div>
<p>The output will be the same as before, but the log file is no longer appended
to, so the messages from earlier runs are lost.</p>
</div>
<div class="section" id="logging-from-multiple-modules">
<h3>Logging from multiple modules<a class="headerlink" href="#logging-from-multiple-modules" title="Permalink to this headline">¶</a></h3>
<p>If your program consists of multiple modules, here’s an example of how you
could organize logging in it:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="c1"># myapp.py</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">mylib</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;myapp.log&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Started&#39;</span><span class="p">)</span>
    <span class="n">mylib</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Finished&#39;</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="c1"># mylib.py</span>
<span class="kn">import</span> <span class="nn">logging</span>

<span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Doing something&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you run <em>myapp.py</em>, you should see this in <em>myapp.log</em>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Started</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Doing</span> <span class="n">something</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Finished</span>
</pre></div>
</div>
<p>which is hopefully what you were expecting to see. You can generalize this to
multiple modules, using the pattern in <em>mylib.py</em>. Note that for this simple
usage pattern, you won’t know, by looking in the log file, <em>where</em> in your
application your messages came from, apart from looking at the event
description. If you want to track the location of your messages, you’ll need
to refer to the documentation beyond the tutorial level – see
<a class="reference internal" href="#logging-advanced-tutorial"><span class="std std-ref">Advanced Logging Tutorial</span></a>.</p>
</div>
<div class="section" id="logging-variable-data">
<h3>Logging variable data<a class="headerlink" href="#logging-variable-data" title="Permalink to this headline">¶</a></h3>
<p>To log variable data, use a format string for the event description message and
append the variable data as arguments. For example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> before you </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;Look&#39;</span><span class="p">,</span> <span class="s1">&#39;leap!&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>will display:</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>WARNING:root:Look before you leap!
</pre></div>
</div>
<p>As you can see, merging of variable data into the event description message
uses the old, %-style of string formatting. This is for backwards
compatibility: the logging package pre-dates newer formatting options such as
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal"><span class="pre">str.format()</span></code></a> and <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal"><span class="pre">string.Template</span></code></a>. These newer formatting
options <em>are</em> supported, but exploring them is outside the scope of this
tutorial: see <a class="reference internal" href="logging-cookbook.html#formatting-styles"><span class="std std-ref">Using particular formatting styles throughout your application</span></a> for more information.</p>
</div>
<div class="section" id="changing-the-format-of-displayed-messages">
<h3>Changing the format of displayed messages<a class="headerlink" href="#changing-the-format-of-displayed-messages" title="Permalink to this headline">¶</a></h3>
<p>To change the format which is used to display messages, you need to
specify the format you want to use:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(levelname)s</span><span class="s1">:</span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;This message should appear on the console&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;So should this&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;And this, too&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which would print:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">DEBUG</span><span class="p">:</span><span class="n">This</span> <span class="n">message</span> <span class="n">should</span> <span class="n">appear</span> <span class="n">on</span> <span class="n">the</span> <span class="n">console</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">So</span> <span class="n">should</span> <span class="n">this</span>
<span class="n">WARNING</span><span class="p">:</span><span class="n">And</span> <span class="n">this</span><span class="p">,</span> <span class="n">too</span>
</pre></div>
</div>
<p>Notice that the ‘root’ which appeared in earlier examples has disappeared. For
a full set of things that can appear in format strings, you can refer to the
documentation for <a class="reference internal" href="../library/logging.html#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>, but for simple usage, you just
need the <em>levelname</em> (severity), <em>message</em> (event description, including
variable data) and perhaps to display when the event occurred. This is
described in the next section.</p>
</div>
<div class="section" id="displaying-the-date-time-in-messages">
<h3>Displaying the date/time in messages<a class="headerlink" href="#displaying-the-date-time-in-messages" title="Permalink to this headline">¶</a></h3>
<p>To display the date and time of an event, you would place ‘%(asctime)s’ in
your format string:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;is when this event was logged.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which should print something like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="mi">2010</span><span class="o">-</span><span class="mi">12</span><span class="o">-</span><span class="mi">12</span> <span class="mi">11</span><span class="p">:</span><span class="mi">41</span><span class="p">:</span><span class="mi">42</span><span class="p">,</span><span class="mi">612</span> <span class="ow">is</span> <span class="n">when</span> <span class="n">this</span> <span class="n">event</span> <span class="n">was</span> <span class="n">logged</span><span class="o">.</span>
</pre></div>
</div>
<p>The default format for date/time display (shown above) is ISO8601. If you need
more control over the formatting of the date/time, provide a <em>datefmt</em>
argument to <code class="docutils literal"><span class="pre">basicConfig</span></code>, as in this example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">datefmt</span><span class="o">=</span><span class="s1">&#39;%m/</span><span class="si">%d</span><span class="s1">/%Y %I:%M:%S %p&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;is when this event was logged.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which would display something like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="mi">12</span><span class="o">/</span><span class="mi">12</span><span class="o">/</span><span class="mi">2010</span> <span class="mi">11</span><span class="p">:</span><span class="mi">46</span><span class="p">:</span><span class="mi">36</span> <span class="n">AM</span> <span class="ow">is</span> <span class="n">when</span> <span class="n">this</span> <span class="n">event</span> <span class="n">was</span> <span class="n">logged</span><span class="o">.</span>
</pre></div>
</div>
<p>The format of the <em>datefmt</em> argument is the same as supported by
<a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal"><span class="pre">time.strftime()</span></code></a>.</p>
</div>
<div class="section" id="next-steps">
<h3>Next Steps<a class="headerlink" href="#next-steps" title="Permalink to this headline">¶</a></h3>
<p>That concludes the basic tutorial. It should be enough to get you up and
running with logging. There’s a lot more that the logging package offers, but
to get the best out of it, you’ll need to invest a little more of your time in
reading the following sections. If you’re ready for that, grab some of your
favourite beverage and carry on.</p>
<p>If your logging needs are simple, then use the above examples to incorporate
logging into your own scripts, and if you run into problems or don’t
understand something, please post a question on the comp.lang.python Usenet
group (available at <a class="reference external" href="https://groups.google.com/group/comp.lang.python">https://groups.google.com/group/comp.lang.python</a>) and you
should receive help before too long.</p>
<p>Still here? You can carry on reading the next few sections, which provide a
slightly more advanced/in-depth tutorial than the basic one above. After that,
you can take a look at the <a class="reference internal" href="logging-cookbook.html#logging-cookbook"><span class="std std-ref">Logging Cookbook</span></a>.</p>
</div>
</div>
<div class="section" id="advanced-logging-tutorial">
<span id="logging-advanced-tutorial"></span><h2>Advanced Logging Tutorial<a class="headerlink" href="#advanced-logging-tutorial" title="Permalink to this headline">¶</a></h2>
<p>The logging library takes a modular approach and offers several categories
of components: loggers, handlers, filters, and formatters.</p>
<ul class="simple">
<li>Loggers expose the interface that application code directly uses.</li>
<li>Handlers send the log records (created by loggers) to the appropriate
destination.</li>
<li>Filters provide a finer grained facility for determining which log records
to output.</li>
<li>Formatters specify the layout of log records in the final output.</li>
</ul>
<p>Log event information is passed between loggers, handlers, filters and
formatters in a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a> instance.</p>
<p>Logging is performed by calling methods on instances of the <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a>
class (hereafter called <em class="dfn">loggers</em>). Each instance has a name, and they are
conceptually arranged in a namespace hierarchy using dots (periods) as
separators. For example, a logger named ‘scan’ is the parent of loggers
‘scan.text’, ‘scan.html’ and ‘scan.pdf’. Logger names can be anything you want,
and indicate the area of an application in which a logged message originates.</p>
<p>A good convention to use when naming loggers is to use a module-level logger,
in each module which uses logging, named as follows:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>
</pre></div>
</div>
<p>This means that logger names track the package/module hierarchy, and it’s
intuitively obvious where events are logged just from the logger name.</p>
<p>The root of the hierarchy of loggers is called the root logger. That’s the
logger used by the functions <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">warning()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">error()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">critical()</span></code></a>, which just call the same-named method of
the root logger. The functions and the methods have the same signatures. The
root logger’s name is printed as ‘root’ in the logged output.</p>
<p>It is, of course, possible to log messages to different destinations. Support
is included in the package for writing log messages to files, HTTP GET/POST
locations, email via SMTP, generic sockets, queues, or OS-specific logging
mechanisms such as syslog or the Windows NT event log. Destinations are served
by <em class="dfn">handler</em> classes. You can create your own log destination class if
you have special requirements not met by any of the built-in handler classes.</p>
<p>By default, no destination is set for any logging messages. You can specify
a destination (such as console or file) by using <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> as in the
tutorial examples. If you call the functions  <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal"><span class="pre">info()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal"><span class="pre">error()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal"><span class="pre">critical()</span></code></a>, they will check to see
if no destination is set; and if one is not set, they will set a destination
of the console (<code class="docutils literal"><span class="pre">sys.stderr</span></code>) and a default format for the displayed
message before delegating to the root logger to do the actual message output.</p>
<p>The default format set by <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> for messages is:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">severity</span><span class="p">:</span><span class="n">logger</span> <span class="n">name</span><span class="p">:</span><span class="n">message</span>
</pre></div>
</div>
<p>You can change this by passing a format string to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></code></a> with the
<em>format</em> keyword argument. For all options regarding how a format string is
constructed, see <a class="reference internal" href="../library/logging.html#formatter-objects"><span class="std std-ref">Formatter Objects</span></a>.</p>
<div class="section" id="logging-flow">
<h3>Logging Flow<a class="headerlink" href="#logging-flow" title="Permalink to this headline">¶</a></h3>
<p>The flow of log event information in loggers and handlers is illustrated in the
following diagram.</p>
<img alt="../_images/logging_flow.png" src="../_images/logging_flow.png" />
</div>
<div class="section" id="loggers">
<h3>Loggers<a class="headerlink" href="#loggers" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a> objects have a threefold job.  First, they expose several
methods to application code so that applications can log messages at runtime.
Second, logger objects determine which log messages to act upon based upon
severity (the default filtering facility) or filter objects.  Third, logger
objects pass along relevant log messages to all interested log handlers.</p>
<p>The most widely used methods on logger objects fall into two categories:
configuration and message sending.</p>
<p>These are the most common configuration methods:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/logging.html#logging.Logger.setLevel" title="logging.Logger.setLevel"><code class="xref py py-meth docutils literal"><span class="pre">Logger.setLevel()</span></code></a> specifies the lowest-severity log message a logger
will handle, where debug is the lowest built-in severity level and critical
is the highest built-in severity.  For example, if the severity level is
INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
and will ignore DEBUG messages.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal"><span class="pre">Logger.addHandler()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeHandler" title="logging.Logger.removeHandler"><code class="xref py py-meth docutils literal"><span class="pre">Logger.removeHandler()</span></code></a> add and remove
handler objects from the logger object.  Handlers are covered in more detail
in <a class="reference internal" href="#handler-basic"><span class="std std-ref">Handlers</span></a>.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.addFilter" title="logging.Logger.addFilter"><code class="xref py py-meth docutils literal"><span class="pre">Logger.addFilter()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeFilter" title="logging.Logger.removeFilter"><code class="xref py py-meth docutils literal"><span class="pre">Logger.removeFilter()</span></code></a> add and remove filter
objects from the logger object.  Filters are covered in more detail in
<a class="reference internal" href="../library/logging.html#filter"><span class="std std-ref">Filter Objects</span></a>.</li>
</ul>
<p>You don’t need to always call these methods on every logger you create. See the
last two paragraphs in this section.</p>
<p>With the logger object configured, the following methods create log messages:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/logging.html#logging.Logger.debug" title="logging.Logger.debug"><code class="xref py py-meth docutils literal"><span class="pre">Logger.debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.info" title="logging.Logger.info"><code class="xref py py-meth docutils literal"><span class="pre">Logger.info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.warning" title="logging.Logger.warning"><code class="xref py py-meth docutils literal"><span class="pre">Logger.warning()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><code class="xref py py-meth docutils literal"><span class="pre">Logger.error()</span></code></a>, and <a class="reference internal" href="../library/logging.html#logging.Logger.critical" title="logging.Logger.critical"><code class="xref py py-meth docutils literal"><span class="pre">Logger.critical()</span></code></a> all create log records with
a message and a level that corresponds to their respective method names. The
message is actually a format string, which may contain the standard string
substitution syntax of <code class="docutils literal"><span class="pre">%s</span></code>, <code class="docutils literal"><span class="pre">%d</span></code>, <code class="docutils literal"><span class="pre">%f</span></code>, and so on.  The
rest of their arguments is a list of objects that correspond with the
substitution fields in the message.  With regard to <code class="docutils literal"><span class="pre">**kwargs</span></code>, the
logging methods care only about a keyword of <code class="docutils literal"><span class="pre">exc_info</span></code> and use it to
determine whether to log exception information.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal"><span class="pre">Logger.exception()</span></code></a> creates a log message similar to
<a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><code class="xref py py-meth docutils literal"><span class="pre">Logger.error()</span></code></a>.  The difference is that <a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal"><span class="pre">Logger.exception()</span></code></a> dumps a
stack trace along with it.  Call this method only from an exception handler.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.log" title="logging.Logger.log"><code class="xref py py-meth docutils literal"><span class="pre">Logger.log()</span></code></a> takes a log level as an explicit argument.  This is a
little more verbose for logging messages than using the log level convenience
methods listed above, but this is how to log at custom log levels.</li>
</ul>
<p><a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal"><span class="pre">getLogger()</span></code></a> returns a reference to a logger instance with the specified
name if it is provided, or <code class="docutils literal"><span class="pre">root</span></code> if not.  The names are period-separated
hierarchical structures.  Multiple calls to <a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal"><span class="pre">getLogger()</span></code></a> with the same name
will return a reference to the same logger object.  Loggers that are further
down in the hierarchical list are children of loggers higher up in the list.
For example, given a logger with a name of <code class="docutils literal"><span class="pre">foo</span></code>, loggers with names of
<code class="docutils literal"><span class="pre">foo.bar</span></code>, <code class="docutils literal"><span class="pre">foo.bar.baz</span></code>, and <code class="docutils literal"><span class="pre">foo.bam</span></code> are all descendants of <code class="docutils literal"><span class="pre">foo</span></code>.</p>
<p>Loggers have a concept of <em>effective level</em>. If a level is not explicitly set
on a logger, the level of its parent is used instead as its effective level.
If the parent has no explicit level set, <em>its</em> parent is examined, and so on -
all ancestors are searched until an explicitly set level is found. The root
logger always has an explicit level set (<code class="docutils literal"><span class="pre">WARNING</span></code> by default). When deciding
whether to process an event, the effective level of the logger is used to
determine whether the event is passed to the logger’s handlers.</p>
<p>Child loggers propagate messages up to the handlers associated with their
ancestor loggers. Because of this, it is unnecessary to define and configure
handlers for all the loggers an application uses. It is sufficient to
configure handlers for a top-level logger and create child loggers as needed.
(You can, however, turn off propagation by setting the <em>propagate</em>
attribute of a logger to <code class="docutils literal"><span class="pre">False</span></code>.)</p>
</div>
<div class="section" id="handlers">
<span id="handler-basic"></span><h3>Handlers<a class="headerlink" href="#handlers" title="Permalink to this headline">¶</a></h3>
<p><code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> objects are responsible for dispatching the
appropriate log messages (based on the log messages’ severity) to the handler’s
specified destination.  <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a> objects can add zero or more handler
objects to themselves with an <a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal"><span class="pre">addHandler()</span></code></a> method.  As an example
scenario, an application may want to send all log messages to a log file, all
log messages of error or higher to stdout, and all messages of critical to an
email address. This scenario requires three individual handlers where each
handler is responsible for sending messages of a specific severity to a specific
location.</p>
<p>The standard library includes quite a few handler types (see
<a class="reference internal" href="#useful-handlers"><span class="std std-ref">Useful Handlers</span></a>); the tutorials use mainly <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> and
<a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal"><span class="pre">FileHandler</span></code></a> in its examples.</p>
<p>There are very few methods in a handler for application developers to concern
themselves with.  The only handler methods that seem relevant for application
developers who are using the built-in handler objects (that is, not creating
custom handlers) are the following configuration methods:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../library/logging.html#logging.Handler.setLevel" title="logging.Handler.setLevel"><code class="xref py py-meth docutils literal"><span class="pre">setLevel()</span></code></a> method, just as in logger objects, specifies the
lowest severity that will be dispatched to the appropriate destination.  Why
are there two <code class="xref py py-func docutils literal"><span class="pre">setLevel()</span></code> methods?  The level set in the logger
determines which severity of messages it will pass to its handlers.  The level
set in each handler determines which messages that handler will send on.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Handler.setFormatter" title="logging.Handler.setFormatter"><code class="xref py py-meth docutils literal"><span class="pre">setFormatter()</span></code></a> selects a Formatter object for this handler to
use.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Handler.addFilter" title="logging.Handler.addFilter"><code class="xref py py-meth docutils literal"><span class="pre">addFilter()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Handler.removeFilter" title="logging.Handler.removeFilter"><code class="xref py py-meth docutils literal"><span class="pre">removeFilter()</span></code></a> respectively
configure and deconfigure filter objects on handlers.</li>
</ul>
<p>Application code should not directly instantiate and use instances of
<code class="xref py py-class docutils literal"><span class="pre">Handler</span></code>.  Instead, the <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> class is a base class that
defines the interface that all handlers should have and establishes some
default behavior that child classes can use (or override).</p>
</div>
<div class="section" id="formatters">
<h3>Formatters<a class="headerlink" href="#formatters" title="Permalink to this headline">¶</a></h3>
<p>Formatter objects configure the final order, structure, and contents of the log
message.  Unlike the base <code class="xref py py-class docutils literal"><span class="pre">logging.Handler</span></code> class, application code may
instantiate formatter classes, although you could likely subclass the formatter
if your application needs special behavior.  The constructor takes three
optional arguments – a message format string, a date format string and a style
indicator.</p>
<dl class="method">
<dt id="logging.logging.Formatter.__init__">
<code class="descclassname">logging.Formatter.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>fmt=None</em>, <em>datefmt=None</em>, <em>style='%'</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.logging.Formatter.__init__" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>If there is no message format string, the default is to use the
raw message.  If there is no date format string, the default date format is:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="o">%</span><span class="n">Y</span><span class="o">-%</span><span class="n">m</span><span class="o">-%</span><span class="n">d</span> <span class="o">%</span><span class="n">H</span><span class="p">:</span><span class="o">%</span><span class="n">M</span><span class="p">:</span><span class="o">%</span><span class="n">S</span>
</pre></div>
</div>
<p>with the milliseconds tacked on at the end. The <code class="docutils literal"><span class="pre">style</span></code> is one of <cite>%</cite>, ‘{‘
or ‘$’. If one of these is not specified, then ‘%’ will be used.</p>
<p>If the <code class="docutils literal"><span class="pre">style</span></code> is ‘%’, the message format string uses
<code class="docutils literal"><span class="pre">%(&lt;dictionary</span> <span class="pre">key&gt;)s</span></code> styled string substitution; the possible keys are
documented in <a class="reference internal" href="../library/logging.html#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>. If the style is ‘{‘, the message
format string is assumed to be compatible with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal"><span class="pre">str.format()</span></code></a> (using
keyword arguments), while if the style is ‘$’ then the message format string
should conform to what is expected by <a class="reference internal" href="../library/string.html#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal"><span class="pre">string.Template.substitute()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.2: </span>Added the <code class="docutils literal"><span class="pre">style</span></code> parameter.</p>
</div>
<p>The following message format string will log the time in a human-readable
format, the severity of the message, and the contents of the message, in that
order:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
</pre></div>
</div>
<p>Formatters use a user-configurable function to convert the creation time of a
record to a tuple. By default, <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal"><span class="pre">time.localtime()</span></code></a> is used; to change this
for a particular formatter instance, set the <code class="docutils literal"><span class="pre">converter</span></code> attribute of the
instance to a function with the same signature as <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal"><span class="pre">time.localtime()</span></code></a> or
<a class="reference internal" href="../library/time.html#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal"><span class="pre">time.gmtime()</span></code></a>. To change it for all formatters, for example if you want
all logging times to be shown in GMT, set the <code class="docutils literal"><span class="pre">converter</span></code> attribute in the
Formatter class (to <code class="docutils literal"><span class="pre">time.gmtime</span></code> for GMT display).</p>
</div>
<div class="section" id="configuring-logging">
<h3>Configuring Logging<a class="headerlink" href="#configuring-logging" title="Permalink to this headline">¶</a></h3>
<p>Programmers can configure logging in three ways:</p>
<ol class="arabic simple">
<li>Creating loggers, handlers, and formatters explicitly using Python
code that calls the configuration methods listed above.</li>
<li>Creating a logging config file and reading it using the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></code></a>
function.</li>
<li>Creating a dictionary of configuration information and passing it
to the <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></code></a> function.</li>
</ol>
<p>For the reference documentation on the last two options, see
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span class="std std-ref">Configuration functions</span></a>.  The following example configures a very simple
logger, a console handler, and a simple formatter using Python code:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>

<span class="c1"># create logger</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simple_example&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>

<span class="c1"># create console handler and set level to debug</span>
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>

<span class="c1"># create formatter</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>

<span class="c1"># add formatter to ch</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>

<span class="c1"># add ch to logger</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>

<span class="c1"># &#39;application&#39; code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Running this module from the command line produces the following output:</p>
<div class="highlight-shell-session"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_module.py
<span class="go">2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message</span>
<span class="go">2005-03-19 15:10:26,620 - simple_example - INFO - info message</span>
<span class="go">2005-03-19 15:10:26,695 - simple_example - WARNING - warn message</span>
<span class="go">2005-03-19 15:10:26,697 - simple_example - ERROR - error message</span>
<span class="go">2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message</span>
</pre></div>
</div>
<p>The following Python module creates a logger, handler, and formatter nearly
identical to those in the example listed above, with the only difference being
the names of the objects:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>

<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">fileConfig</span><span class="p">(</span><span class="s1">&#39;logging.conf&#39;</span><span class="p">)</span>

<span class="c1"># create logger</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simpleExample&#39;</span><span class="p">)</span>

<span class="c1"># &#39;application&#39; code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here is the logging.conf file:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">loggers</span><span class="p">]</span>
<span class="n">keys</span><span class="o">=</span><span class="n">root</span><span class="p">,</span><span class="n">simpleExample</span>

<span class="p">[</span><span class="n">handlers</span><span class="p">]</span>
<span class="n">keys</span><span class="o">=</span><span class="n">consoleHandler</span>

<span class="p">[</span><span class="n">formatters</span><span class="p">]</span>
<span class="n">keys</span><span class="o">=</span><span class="n">simpleFormatter</span>

<span class="p">[</span><span class="n">logger_root</span><span class="p">]</span>
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
<span class="n">handlers</span><span class="o">=</span><span class="n">consoleHandler</span>

<span class="p">[</span><span class="n">logger_simpleExample</span><span class="p">]</span>
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
<span class="n">handlers</span><span class="o">=</span><span class="n">consoleHandler</span>
<span class="n">qualname</span><span class="o">=</span><span class="n">simpleExample</span>
<span class="n">propagate</span><span class="o">=</span><span class="mi">0</span>

<span class="p">[</span><span class="n">handler_consoleHandler</span><span class="p">]</span>
<span class="n">class</span><span class="o">=</span><span class="n">StreamHandler</span>
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
<span class="n">formatter</span><span class="o">=</span><span class="n">simpleFormatter</span>
<span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,)</span>

<span class="p">[</span><span class="n">formatter_simpleFormatter</span><span class="p">]</span>
<span class="nb">format</span><span class="o">=%</span><span class="p">(</span><span class="n">asctime</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">name</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">levelname</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">message</span><span class="p">)</span><span class="n">s</span>
<span class="n">datefmt</span><span class="o">=</span>
</pre></div>
</div>
<p>The output is nearly identical to that of the non-config-file-based example:</p>
<div class="highlight-shell-session"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_config.py
<span class="go">2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message</span>
<span class="go">2005-03-19 15:38:55,979 - simpleExample - INFO - info message</span>
<span class="go">2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message</span>
<span class="go">2005-03-19 15:38:56,055 - simpleExample - ERROR - error message</span>
<span class="go">2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message</span>
</pre></div>
</div>
<p>You can see that the config file approach has a few advantages over the Python
code approach, mainly separation of configuration and code and the ability of
noncoders to easily modify the logging properties.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>The <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></code></a> function takes a default parameter,
<code class="docutils literal"><span class="pre">disable_existing_loggers</span></code>, which defaults to <code class="docutils literal"><span class="pre">True</span></code> for reasons of
backward compatibility. This may or may not be what you want, since it
will cause any loggers existing before the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal"><span class="pre">fileConfig()</span></code></a> call to
be disabled unless they (or an ancestor) are explicitly named in the
configuration.  Please refer to the reference documentation for more
information, and specify <code class="docutils literal"><span class="pre">False</span></code> for this parameter if you wish.</p>
<p class="last">The dictionary passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></code></a> can also specify a Boolean
value with key <code class="docutils literal"><span class="pre">disable_existing_loggers</span></code>, which if not specified
explicitly in the dictionary also defaults to being interpreted as
<code class="docutils literal"><span class="pre">True</span></code>.  This leads to the logger-disabling behaviour described above,
which may not be what you want - in which case, provide the key
explicitly with a value of <code class="docutils literal"><span class="pre">False</span></code>.</p>
</div>
<p>Note that the class names referenced in config files need to be either relative
to the logging module, or absolute values which can be resolved using normal
import mechanisms. Thus, you could use either
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></code></a> (relative to the logging module) or
<code class="docutils literal"><span class="pre">mypackage.mymodule.MyHandler</span></code> (for a class defined in package <code class="docutils literal"><span class="pre">mypackage</span></code>
and module <code class="docutils literal"><span class="pre">mymodule</span></code>, where <code class="docutils literal"><span class="pre">mypackage</span></code> is available on the Python import
path).</p>
<p>In Python 3.2, a new means of configuring logging has been introduced, using
dictionaries to hold configuration information. This provides a superset of the
functionality of the config-file-based approach outlined above, and is the
recommended configuration method for new applications and deployments. Because
a Python dictionary is used to hold configuration information, and since you
can populate that dictionary using different means, you have more options for
configuration. For example, you can use a configuration file in JSON format,
or, if you have access to YAML processing functionality, a file in YAML
format, to populate the configuration dictionary. Or, of course, you can
construct the dictionary in Python code, receive it in pickled form over a
socket, or use whatever approach makes sense for your application.</p>
<p>Here’s an example of the same configuration as above, in YAML format for
the new dictionary-based approach:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="n">version</span><span class="p">:</span> <span class="mi">1</span>
<span class="n">formatters</span><span class="p">:</span>
  <span class="n">simple</span><span class="p">:</span>
    <span class="nb">format</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
<span class="n">handlers</span><span class="p">:</span>
  <span class="n">console</span><span class="p">:</span>
    <span class="n">class</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span>
    <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
    <span class="n">formatter</span><span class="p">:</span> <span class="n">simple</span>
    <span class="n">stream</span><span class="p">:</span> <span class="n">ext</span><span class="p">:</span><span class="o">//</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span>
<span class="n">loggers</span><span class="p">:</span>
  <span class="n">simpleExample</span><span class="p">:</span>
    <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
    <span class="n">handlers</span><span class="p">:</span> <span class="p">[</span><span class="n">console</span><span class="p">]</span>
    <span class="n">propagate</span><span class="p">:</span> <span class="n">no</span>
<span class="n">root</span><span class="p">:</span>
  <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
  <span class="n">handlers</span><span class="p">:</span> <span class="p">[</span><span class="n">console</span><span class="p">]</span>
</pre></div>
</div>
<p>For more information about logging using a dictionary, see
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span class="std std-ref">Configuration functions</span></a>.</p>
</div>
<div class="section" id="what-happens-if-no-configuration-is-provided">
<h3>What happens if no configuration is provided<a class="headerlink" href="#what-happens-if-no-configuration-is-provided" title="Permalink to this headline">¶</a></h3>
<p>If no logging configuration is provided, it is possible to have a situation
where a logging event needs to be output, but no handlers can be found to
output the event. The behaviour of the logging package in these
circumstances is dependent on the Python version.</p>
<p>For versions of Python prior to 3.2, the behaviour is as follows:</p>
<ul class="simple">
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal"><span class="pre">False</span></code> (production mode), the event is
silently dropped.</li>
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal"><span class="pre">True</span></code> (development mode), a message
‘No handlers could be found for logger X.Y.Z’ is printed once.</li>
</ul>
<p>In Python 3.2 and later, the behaviour is as follows:</p>
<ul class="simple">
<li>The event is output using a ‘handler of last resort’, stored in
<code class="docutils literal"><span class="pre">logging.lastResort</span></code>. This internal handler is not associated with any
logger, and acts like a <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> which writes the
event description message to the current value of <code class="docutils literal"><span class="pre">sys.stderr</span></code> (therefore
respecting any redirections which may be in effect). No formatting is
done on the message - just the bare event description message is printed.
The handler’s level is set to <code class="docutils literal"><span class="pre">WARNING</span></code>, so all events at this and
greater severities will be output.</li>
</ul>
<p>To obtain the pre-3.2 behaviour, <code class="docutils literal"><span class="pre">logging.lastResort</span></code> can be set to <code class="docutils literal"><span class="pre">None</span></code>.</p>
</div>
<div class="section" id="configuring-logging-for-a-library">
<span id="library-config"></span><h3>Configuring Logging for a Library<a class="headerlink" href="#configuring-logging-for-a-library" title="Permalink to this headline">¶</a></h3>
<p>When developing a library which uses logging, you should take care to
document how the library uses logging - for example, the names of loggers
used. Some consideration also needs to be given to its logging configuration.
If the using application does not use logging, and library code makes logging
calls, then (as described in the previous section) events of severity
<code class="docutils literal"><span class="pre">WARNING</span></code> and greater will be printed to <code class="docutils literal"><span class="pre">sys.stderr</span></code>. This is regarded as
the best default behaviour.</p>
<p>If for some reason you <em>don’t</em> want these messages printed in the absence of
any logging configuration, you can attach a do-nothing handler to the top-level
logger for your library. This avoids the message being printed, since a handler
will be always be found for the library’s events: it just doesn’t produce any
output. If the library user configures logging for application use, presumably
that configuration will add some handlers, and if levels are suitably
configured then logging calls made in library code will send output to those
handlers, as normal.</p>
<p>A do-nothing handler is included in the logging package:
<a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> (since Python 3.1). An instance of this handler
could be added to the top-level logger of the logging namespace used by the
library (<em>if</em> you want to prevent your library’s logged events being output to
<code class="docutils literal"><span class="pre">sys.stderr</span></code> in the absence of logging configuration). If all logging by a
library <em>foo</em> is done using loggers with names matching ‘foo.x’, ‘foo.x.y’,
etc. then the code:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">NullHandler</span><span class="p">())</span>
</pre></div>
</div>
<p>should have the desired effect. If an organisation produces a number of
libraries, then the logger name specified can be ‘orgname.foo’ rather than
just ‘foo’.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It is strongly advised that you <em>do not add any handlers other
than</em> <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> <em>to your library’s loggers</em>. This is
because the configuration of handlers is the prerogative of the application
developer who uses your library. The application developer knows their
target audience and what handlers are most appropriate for their
application: if you add handlers ‘under the hood’, you might well interfere
with their ability to carry out unit tests and deliver logs which suit their
requirements.</p>
</div>
</div>
</div>
<div class="section" id="logging-levels">
<h2>Logging Levels<a class="headerlink" href="#logging-levels" title="Permalink to this headline">¶</a></h2>
<p>The numeric values of logging levels are given in the following table. These are
primarily of interest if you want to define your own levels, and need them to
have specific values relative to the predefined levels. If you define a level
with the same numeric value, it overwrites the predefined value; the predefined
name is lost.</p>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">Numeric value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal"><span class="pre">CRITICAL</span></code></td>
<td>50</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">ERROR</span></code></td>
<td>40</td>
</tr>
<tr class="row-even"><td><code class="docutils literal"><span class="pre">WARNING</span></code></td>
<td>30</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">INFO</span></code></td>
<td>20</td>
</tr>
<tr class="row-even"><td><code class="docutils literal"><span class="pre">DEBUG</span></code></td>
<td>10</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal"><span class="pre">NOTSET</span></code></td>
<td>0</td>
</tr>
</tbody>
</table>
<p>Levels can also be associated with loggers, being set either by the developer or
through loading a saved logging configuration. When a logging method is called
on a logger, the logger compares its own level with the level associated with
the method call. If the logger’s level is higher than the method call’s, no
logging message is actually generated. This is the basic mechanism controlling
the verbosity of logging output.</p>
<p>Logging messages are encoded as instances of the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a>
class. When a logger decides to actually log an event, a
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a> instance is created from the logging message.</p>
<p>Logging messages are subjected to a dispatch mechanism through the use of
<em class="dfn">handlers</em>, which are instances of subclasses of the <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code>
class. Handlers are responsible for ensuring that a logged message (in the form
of a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a>) ends up in a particular location (or set of locations)
which is useful for the target audience for that message (such as end users,
support desk staff, system administrators, developers). Handlers are passed
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal"><span class="pre">LogRecord</span></code></a> instances intended for particular destinations. Each logger
can have zero, one or more handlers associated with it (via the
<a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal"><span class="pre">addHandler()</span></code></a> method of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a>). In addition to any
handlers directly associated with a logger, <em>all handlers associated with all
ancestors of the logger</em> are called to dispatch the message (unless the
<em>propagate</em> flag for a logger is set to a false value, at which point the
passing to ancestor handlers stops).</p>
<p>Just as for loggers, handlers can have levels associated with them. A handler’s
level acts as a filter in the same way as a logger’s level does. If a handler
decides to actually dispatch an event, the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal"><span class="pre">emit()</span></code></a> method is used
to send the message to its destination. Most user-defined subclasses of
<code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> will need to override this <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal"><span class="pre">emit()</span></code></a>.</p>
<div class="section" id="custom-levels">
<span id="id1"></span><h3>Custom Levels<a class="headerlink" href="#custom-levels" title="Permalink to this headline">¶</a></h3>
<p>Defining your own levels is possible, but should not be necessary, as the
existing levels have been chosen on the basis of practical experience.
However, if you are convinced that you need custom levels, great care should
be exercised when doing this, and it is possibly <em>a very bad idea to define
custom levels if you are developing a library</em>. That’s because if multiple
library authors all define their own custom levels, there is a chance that
the logging output from such multiple libraries used together will be
difficult for the using developer to control and/or interpret, because a
given numeric value might mean different things for different libraries.</p>
</div>
</div>
<div class="section" id="useful-handlers">
<span id="id2"></span><h2>Useful Handlers<a class="headerlink" href="#useful-handlers" title="Permalink to this headline">¶</a></h2>
<p>In addition to the base <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> class, many useful subclasses are
provided:</p>
<ol class="arabic simple">
<li><a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> instances send messages to streams (file-like
objects).</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal"><span class="pre">FileHandler</span></code></a> instances send messages to disk files.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.BaseRotatingHandler" title="logging.handlers.BaseRotatingHandler"><code class="xref py py-class docutils literal"><span class="pre">BaseRotatingHandler</span></code></a> is the base class for handlers that
rotate log files at a certain point. It is not meant to be  instantiated
directly. Instead, use <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></code></a> or
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></code></a>.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></code></a> instances send messages to disk
files, with support for maximum log file sizes and log file rotation.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></code></a> instances send messages to
disk files, rotating the log file at certain timed intervals.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></code></a> instances send messages to TCP/IP
sockets. Since 3.4, Unix domain sockets are also supported.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><code class="xref py py-class docutils literal"><span class="pre">DatagramHandler</span></code></a> instances send messages to UDP
sockets. Since 3.4, Unix domain sockets are also supported.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><code class="xref py py-class docutils literal"><span class="pre">SMTPHandler</span></code></a> instances send messages to a designated
email address.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></code></a> instances send messages to a Unix
syslog daemon, possibly on a remote machine.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><code class="xref py py-class docutils literal"><span class="pre">NTEventLogHandler</span></code></a> instances send messages to a
Windows NT/2000/XP event log.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal"><span class="pre">MemoryHandler</span></code></a> instances send messages to a buffer
in memory, which is flushed whenever specific criteria are met.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code class="xref py py-class docutils literal"><span class="pre">HTTPHandler</span></code></a> instances send messages to an HTTP
server using either <code class="docutils literal"><span class="pre">GET</span></code> or <code class="docutils literal"><span class="pre">POST</span></code> semantics.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal"><span class="pre">WatchedFileHandler</span></code></a> instances watch the file they are
logging to. If the file changes, it is closed and reopened using the file
name. This handler is only useful on Unix-like systems; Windows does not
support the underlying mechanism used.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code class="xref py py-class docutils literal"><span class="pre">QueueHandler</span></code></a> instances send messages to a queue, such as
those implemented in the <a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal"><span class="pre">queue</span></code></a> or <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></code></a> modules.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> instances do nothing with error messages. They are used
by library developers who want to use logging, but want to avoid the ‘No
handlers could be found for logger XXX’ message which can be displayed if
the library user has not configured logging. See <a class="reference internal" href="#library-config"><span class="std std-ref">Configuring Logging for a Library</span></a> for
more information.</li>
</ol>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.1: </span>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a> class.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.2: </span>The <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.QueueHandler" title="logging.handlers.QueueHandler"><code class="xref py py-class docutils literal"><span class="pre">QueueHandler</span></code></a> class.</p>
</div>
<p>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal"><span class="pre">NullHandler</span></code></a>, <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal"><span class="pre">StreamHandler</span></code></a> and <a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal"><span class="pre">FileHandler</span></code></a>
classes are defined in the core logging package. The other handlers are
defined in a sub- module, <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></code></a>. (There is also another
sub-module, <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.config</span></code></a>, for configuration functionality.)</p>
<p>Logged messages are formatted for presentation through instances of the
<a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal"><span class="pre">Formatter</span></code></a> class. They are initialized with a format string suitable for
use with the % operator and a dictionary.</p>
<p>For formatting multiple messages in a batch, instances of
<code class="xref py py-class docutils literal"><span class="pre">BufferingFormatter</span></code> can be used. In addition to the format
string (which is applied to each message in the batch), there is provision for
header and trailer format strings.</p>
<p>When filtering based on logger level and/or handler level is not enough,
instances of <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal"><span class="pre">Filter</span></code></a> can be added to both <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal"><span class="pre">Logger</span></code></a> and
<code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> instances (through their <a class="reference internal" href="../library/logging.html#logging.Handler.addFilter" title="logging.Handler.addFilter"><code class="xref py py-meth docutils literal"><span class="pre">addFilter()</span></code></a> method).
Before deciding to process a message further, both loggers and handlers consult
all their filters for permission. If any filter returns a false value, the
message is not processed further.</p>
<p>The basic <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal"><span class="pre">Filter</span></code></a> functionality allows filtering by specific logger
name. If this feature is used, messages sent to the named logger and its
children are allowed through the filter, and all others dropped.</p>
</div>
<div class="section" id="exceptions-raised-during-logging">
<span id="logging-exceptions"></span><h2>Exceptions raised during logging<a class="headerlink" href="#exceptions-raised-during-logging" title="Permalink to this headline">¶</a></h2>
<p>The logging package is designed to swallow exceptions which occur while logging
in production. This is so that errors which occur while handling logging events
- such as logging misconfiguration, network or other similar errors - do not
cause the application using logging to terminate prematurely.</p>
<p><a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-class docutils literal"><span class="pre">SystemExit</span></code></a> and <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-class docutils literal"><span class="pre">KeyboardInterrupt</span></code></a> exceptions are never
swallowed. Other exceptions which occur during the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal"><span class="pre">emit()</span></code></a> method
of a <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code> subclass are passed to its <a class="reference internal" href="../library/logging.html#logging.Handler.handleError" title="logging.Handler.handleError"><code class="xref py py-meth docutils literal"><span class="pre">handleError()</span></code></a>
method.</p>
<p>The default implementation of <a class="reference internal" href="../library/logging.html#logging.Handler.handleError" title="logging.Handler.handleError"><code class="xref py py-meth docutils literal"><span class="pre">handleError()</span></code></a> in <code class="xref py py-class docutils literal"><span class="pre">Handler</span></code>
checks to see if a module-level variable, <code class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></code>, is set. If
set, a traceback is printed to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal"><span class="pre">sys.stderr</span></code></a>. If not set, the exception is
swallowed.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The default value of <code class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></code> is <code class="docutils literal"><span class="pre">True</span></code>. This is
because during development, you typically want to be notified of any
exceptions that occur. It’s advised that you set <code class="xref py py-data docutils literal"><span class="pre">raiseExceptions</span></code> to
<code class="docutils literal"><span class="pre">False</span></code> for production usage.</p>
</div>
</div>
<div class="section" id="using-arbitrary-objects-as-messages">
<span id="arbitrary-object-messages"></span><h2>Using arbitrary objects as messages<a class="headerlink" href="#using-arbitrary-objects-as-messages" title="Permalink to this headline">¶</a></h2>
<p>In the preceding sections and examples, it has been assumed that the message
passed when logging the event is a string. However, this is not the only
possibility. You can pass an arbitrary object as a message, and its
<a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal"><span class="pre">__str__()</span></code></a> method will be called when the logging system needs to
convert it to a string representation. In fact, if you want to, you can avoid
computing a string representation altogether - for example, the
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></code></a> emits an event by pickling it and sending it
over the wire.</p>
</div>
<div class="section" id="optimization">
<h2>Optimization<a class="headerlink" href="#optimization" title="Permalink to this headline">¶</a></h2>
<p>Formatting of message arguments is deferred until it cannot be avoided.
However, computing the arguments passed to the logging method can also be
expensive, and you may want to avoid doing it if the logger will just throw
away your event. To decide what to do, you can call the
<a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></code></a> method which takes a level argument and returns
true if the event would be created by the Logger for that level of call.
You can write code like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">logger</span><span class="o">.</span><span class="n">isEnabledFor</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">):</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Message with </span><span class="si">%s</span><span class="s1">, </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">expensive_func1</span><span class="p">(),</span>
                                        <span class="n">expensive_func2</span><span class="p">())</span>
</pre></div>
</div>
<p>so that if the logger’s threshold is set above <code class="docutils literal"><span class="pre">DEBUG</span></code>, the calls to
<code class="xref py py-func docutils literal"><span class="pre">expensive_func1()</span></code> and <code class="xref py py-func docutils literal"><span class="pre">expensive_func2()</span></code> are never made.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In some cases, <a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></code></a> can itself be more
expensive than you’d like (e.g. for deeply nested loggers where an explicit
level is only set high up in the logger hierarchy). In such cases (or if you
want to avoid calling a method in tight loops), you can cache the result of a
call to <a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal"><span class="pre">isEnabledFor()</span></code></a> in a local or instance variable, and use
that instead of calling the method each time. Such a cached value would only
need to be recomputed when the logging configuration changes dynamically
while the application is running (which is not all that common).</p>
</div>
<p>There are other optimizations which can be made for specific applications which
need more precise control over what logging information is collected. Here’s a
list of things you can do to avoid processing during logging which you don’t
need:</p>
<table border="1" class="docutils">
<colgroup>
<col width="54%" />
<col width="46%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">What you don’t want to collect</th>
<th class="head">How to avoid collecting it</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Information about where calls were made from.</td>
<td>Set <code class="docutils literal"><span class="pre">logging._srcfile</span></code> to <code class="docutils literal"><span class="pre">None</span></code>.
This avoids calling
<a class="reference internal" href="../library/sys.html#sys._getframe" title="sys._getframe"><code class="xref py py-func docutils literal"><span class="pre">sys._getframe()</span></code></a>, which may help
to speed up your code in environments
like PyPy (which can’t speed up code
that uses <a class="reference internal" href="../library/sys.html#sys._getframe" title="sys._getframe"><code class="xref py py-func docutils literal"><span class="pre">sys._getframe()</span></code></a>), if
and when PyPy supports Python 3.x.</td>
</tr>
<tr class="row-odd"><td>Threading information.</td>
<td>Set <code class="docutils literal"><span class="pre">logging.logThreads</span></code> to <code class="docutils literal"><span class="pre">0</span></code>.</td>
</tr>
<tr class="row-even"><td>Process information.</td>
<td>Set <code class="docutils literal"><span class="pre">logging.logProcesses</span></code> to <code class="docutils literal"><span class="pre">0</span></code>.</td>
</tr>
</tbody>
</table>
<p>Also note that the core logging module only includes the basic handlers. If
you don’t import <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></code></a> and <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.config</span></code></a>, they won’t
take up any memory.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt>Module <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal"><span class="pre">logging</span></code></a></dt>
<dd>API reference for the logging module.</dd>
<dt>Module <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.config</span></code></a></dt>
<dd>Configuration API for the logging module.</dd>
<dt>Module <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal"><span class="pre">logging.handlers</span></code></a></dt>
<dd>Useful handlers included with the logging module.</dd>
</dl>
<p class="last"><a class="reference internal" href="logging-cookbook.html#logging-cookbook"><span class="std std-ref">A logging cookbook</span></a></p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Logging HOWTO</a><ul>
<li><a class="reference internal" href="#basic-logging-tutorial">Basic Logging Tutorial</a><ul>
<li><a class="reference internal" href="#when-to-use-logging">When to use logging</a></li>
<li><a class="reference internal" href="#a-simple-example">A simple example</a></li>
<li><a class="reference internal" href="#logging-to-a-file">Logging to a file</a></li>
<li><a class="reference internal" href="#logging-from-multiple-modules">Logging from multiple modules</a></li>
<li><a class="reference internal" href="#logging-variable-data">Logging variable data</a></li>
<li><a class="reference internal" href="#changing-the-format-of-displayed-messages">Changing the format of displayed messages</a></li>
<li><a class="reference internal" href="#displaying-the-date-time-in-messages">Displaying the date/time in messages</a></li>
<li><a class="reference internal" href="#next-steps">Next Steps</a></li>
</ul>
</li>
<li><a class="reference internal" href="#advanced-logging-tutorial">Advanced Logging Tutorial</a><ul>
<li><a class="reference internal" href="#logging-flow">Logging Flow</a></li>
<li><a class="reference internal" href="#loggers">Loggers</a></li>
<li><a class="reference internal" href="#handlers">Handlers</a></li>
<li><a class="reference internal" href="#formatters">Formatters</a></li>
<li><a class="reference internal" href="#configuring-logging">Configuring Logging</a></li>
<li><a class="reference internal" href="#what-happens-if-no-configuration-is-provided">What happens if no configuration is provided</a></li>
<li><a class="reference internal" href="#configuring-logging-for-a-library">Configuring Logging for a Library</a></li>
</ul>
</li>
<li><a class="reference internal" href="#logging-levels">Logging Levels</a><ul>
<li><a class="reference internal" href="#custom-levels">Custom Levels</a></li>
</ul>
</li>
<li><a class="reference internal" href="#useful-handlers">Useful Handlers</a></li>
<li><a class="reference internal" href="#exceptions-raised-during-logging">Exceptions raised during logging</a></li>
<li><a class="reference internal" href="#using-arbitrary-objects-as-messages">Using arbitrary objects as messages</a></li>
<li><a class="reference internal" href="#optimization">Optimization</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="functional.html"
                        title="previous chapter">Functional Programming HOWTO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="logging-cookbook.html"
                        title="next chapter">Logging Cookbook</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.6/Doc/howto/logging.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             >next</a> |</li>
        <li class="right" >
          <a href="functional.html" title="Functional Programming HOWTO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">en</span>
          <span class="version_switcher_placeholder">3.6.3</span>
          <a href="../index.html">Documentation </a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 2001-2017, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 14, 2017.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.6.4.
    </div>

  </body>
</html>